export function download(data, filename, type) {
  console.debug("Using globals: document, window");
  var file = new Blob([data], { type: type });

  var a = document.createElement("a");
  var url = URL.createObjectURL(file);
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }, 0);
}

// 兼容，翻译已销毁属性名称
export function fix_synonyms(mei) {
  Array.from(mei.getElementsByTagName("node")).forEach((elem) => {
    if (elem.getAttribute("type") == "hyperedge")
      elem.setAttribute("type", "relation");
    if (elem.getAttribute("type") == "metaedge")
      elem.setAttribute("type", "metarelation");
  });
  return mei;
}

export function new_view_elements(layer_element, draw_contexts) {
  var new_view = document.createElement("div");
  new_view.id = "view" + draw_contexts.length;
  new_view.classList.add("view");

  var new_svg = document.createElement("div");
  new_svg.id = "svg" + draw_contexts.length;
  new_svg.classList.add("svg_container");
  new_view.appendChild(new_svg);

  layer_element.appendChild(new_view);
  return [new_view, new_svg];
}

export function random_id(n = 5) {
  return Math.floor(Math.random() * (1 << (n * 4))).toString(16);
}

// 平均数
export function average2(x, y) {
  return (x + y) / 2;
}

// 模7
export function mod(n, m) {
  return ((n % m) + m) % m;
}
// 通过id，查找document中元素
export function get_by_id(doc, id) {
  if (!id) return null;
  if (id[0] == "#") {
    id = id.slice(1);
  }
  var elem = doc.querySelector("[*|id='" + id + "']");
  if (elem) {
    return elem;
  } else {
    return Array.from(doc.getElementsByTagName("*")).find((x) => {
      return x.getAttribute("id") == id || x.getAttribute("xml:id") == id;
    });
  }
}

/**
 * 深度查找。直到找到基本id后返回
 * @param {*} elem
 * @returns id{string}
 */

export function get_id(mei, elem) {
  if (document.contains(elem)) {
    // SVG traversal
    if (!elem.hasAttribute("oldid")) return elem.id;
    else return get_id(document.getElementById(elem.getAttribute("oldid")));
  } else if (elem.hasAttribute("xml:id")) {
    // MEI traversal
    if (elem.hasAttribute("sameas"))
      return get_id(get_by_id(mei, elem.getAttribute("sameas")));
    else if (elem.hasAttribute("corresp"))
      return get_id(get_by_id(mei, elem.getAttribute("corresp")));
    else if (elem.hasAttribute("copyof"))
      return get_id(get_by_id(mei, elem.getAttribute("copyof")));
    else if (elem.hasAttribute("xml:id")) return elem.getAttribute("xml:id");
  }
}

export function add_to_svg_bg(svg_elem, newElement) {
  var sibling = svg_elem.getElementsByClassName("system")[0];
  var parent = sibling.parentNode;
  parent.insertBefore(newElement, sibling);
}

// 音符坐标稍微偏移中心一点
export function note_coords(note) {
  // 计算音符坐标
  return [
    note.getElementsByTagName("use")[0].x.animVal.value + 100,
    note.getElementsByTagName("use")[0].y.animVal.value,
  ];
}
